package com.meizu.control.admin;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONObject;
import com.meizu.entity.Detail;
import com.meizu.entity.Goods;
import com.meizu.entity.GoodsSort;
import com.meizu.entity.Photo;
import com.meizu.service.DetailService;
import com.meizu.service.GoodsService;
import com.meizu.utils.BaseServlet;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
 * 后台商品的控制层操作类
 * @date 2023/4/18
 **/
@WebServlet("/ht/product")
@MultipartConfig
public class ProductServlet extends BaseServlet {
    DetailService ds = new DetailService();
    private GoodsService cs=new GoodsService();
    private Integer sid=0;
    private Integer gstate=0;
    private Integer gid=0;
    String oldName,newName,stoPath,outPath;
    @Override
    public String excute(HttpServletRequest request, HttpServletResponse response) throws Exception {
           List<GoodsSort> goodsSort=cs.selectGoodsSortAsc();
           List<Goods> goods=cs.selectGoodsDetail (1);
        System.out.println (goodsSort);
        System.out.println (goods);
        request.setAttribute ("goodsSort",goodsSort);
           request.setAttribute ("goods",goods);
        return "f:admin/product-list";//跳后台商品列表
    }
    //ajax查询
    /**
     * 根据分类sid查询该分类下的商品
     * 商品的上下架状态的修改
     * @date 2023/4/18
     **/
    public JSONObject selectProduct(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String Gstate=request.getParameter ("gstate");
        String Gid=request.getParameter ("id");
        String Sid=request.getParameter ("sid");
        String sname=request.getParameter ("sname");
        System.out.println (Sid);
        response.setContentType ("application/json;charset=utf-8");
        JSONObject json=new JSONObject ();
        if (Sid!=null){
            if(NumberUtil.isNumber (Sid)){
                sid=Integer.parseInt (Sid);
            }
            List<Goods> goods=cs.selectGoodsDetail (sid);
            json.put ("goods",goods);
            System.out.println (json );
        }
        if (sname!=null&&!" ".equals(sname)){
            Integer i=cs.addGoodSort (sname);
            List<GoodsSort> goodsSort=cs.selectGoodsSortAsc();
            json.put ("goodsort",goodsSort);
        }
        if (Gstate!=null&&Gid!=null){
            if (NumberUtil.isNumber (Gstate)){
                gstate=Integer.valueOf (Gstate);
            }
            if (NumberUtil.isNumber (Gid)){
                gid=Integer.valueOf (Gid);
            }
            cs.updateGstate (gstate,gid);//修改商品上下架状态
        }
        return json;
    }
    /**
     *商品信息的查看详情页面
     **/
    public String productEdit(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String Gid=request.getParameter ("gid");
        if (NumberUtil.isNumber (Gid)){
            gid=Integer.parseInt (Gid);
        }
        Integer sid=cs.selectGoodsOne(gid).getSid();
        System.out.println(cs.selectGoodsOne(gid));
        List<Detail> details=cs.selectGoodDetail(gid);
        request.setAttribute ("details",details);
        request.setAttribute("gid",gid);
        request.setAttribute("sid",sid);
        System.out.println("gid:"+gid+"\tsid:"+sid);
        return "f:admin/product-detail";
    }
    /**
     *发布商品（表单提交）
     **/
    public String productAdd(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String Sid=request.getParameter ("sid");
        String gname=request.getParameter ("gname");
        String gdetail=request.getParameter ("gdetail");
        String gdiscount=request.getParameter ("gdiscount");
        Part part=request.getPart ("gphoto");
        if (NumberUtil.isNumber (Sid)){
            sid=Integer.valueOf (Sid);
        }
        String gphoto=null;
        oldName = part.getSubmittedFileName();//获取文件的原始名字
        if (part.getSize()>0){
            String realPath = request.getServletContext().getRealPath("/");

            //D:\Java03\YF03405\02Java\code\Java\Git\meizu\out\artifacts\meizu_Web_exploded\
            stoPath=realPath.substring(0,realPath.indexOf("out"))+"web/img/htPhoto/";
            outPath=realPath+"img/htPhoto/";
            //上传头像文件
            newName=uniqeName()+getSuffix(oldName);
            FileUtil.writeFromStream(part.getInputStream(),stoPath+newName);//
            gphoto = "../img/htPhoto/"+newName;
        }
        Goods goods=new Goods (sid,gname,gdetail,gdiscount,gphoto);
        Integer gid=cs.insertGoods (goods);
        FileUtil.copyFile(stoPath+newName,outPath+"/"+newName);//
        return "r:/ht/product?v=productManage";
    }
    /**
     *发布商品的 展示页
     **/
    public String productManage(HttpServletRequest request, HttpServletResponse response)throws Exception{
        //查询商品类别
        List<GoodsSort> goodsSorts=cs.selectGoodsSortAsc ();
        //存作用域
        request.setAttribute ("goodsSorts",goodsSorts);
        return "f:admin/product-add";
    }
    /**
     *修改商品表信息操作的 展示页
     **/
    public String productUpdate(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String Gid=request.getParameter ("gid");
        if (NumberUtil.isNumber (Gid)){
            gid=Integer.valueOf (Gid);
        }
        Goods goods=cs.selectGoodsOne (gid);
        request.setAttribute ("goods",goods);
        return "f:admin/product-update";
    }
    /**
    *修改商品表信息(form提交)
     **/
    public String productUpdates(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String id=request.getParameter("gid");
        Integer gid=Integer.valueOf(id);
        List<Goods> Name=cs.selectGoodsName(gid);
        String name=request.getParameter ("gname");
        String detail=request.getParameter ("gdetail");
        String discount=request.getParameter ("gdiscount");
        String photo=request.getParameter("photo");
        String gphoto=null;
        Part part=request.getPart ("uheadshot");
        oldName = part.getSubmittedFileName();//获取文件的原始名字
            if (part.getSize() > 0) {
                System.out.println("输入了图片");
                String realPath = request.getServletContext().getRealPath("/");
                //D:\Java03\YF03405\02Java\code\Java\Git\meizu\out\artifacts\meizu_Web_exploded\
                stoPath = realPath.substring(0, realPath.indexOf("out")) + "web/img/htPhoto/";
                outPath = realPath + "img/htPhoto/";
                newName=uniqeName()+getSuffix(oldName);
                //上传头像文件
                FileUtil.writeFromStream(part.getInputStream(), stoPath + newName);//
                gphoto = "../img/htPhoto/" + newName;
                FileUtil.copyFile(stoPath+newName,outPath+"/"+newName);
            }else {
                gphoto=photo;
            }
        boolean flag=true;
        for (int i = 0; i < Name.size(); i++) {
            if(name.equals(Name.get(i).getGname())){
                flag=false;
                break;
            }
        }
      if (flag){
          cs.updateGoodXX(name,detail,discount,gphoto,gid);
          request.setAttribute("abc","修改成功");//
          return "f:admin/product-update";
      }else {
          session.setAttribute("errorName","商品名称重复！！");
          return "r:/ht/product?v=productUpdate";
      }
    }
    public String selectMH(HttpServletRequest request, HttpServletResponse response)throws Exception{
        String str=request.getParameter("productname");
        List<Goods> goods=cs.selectGoodMF(str);
        List<GoodsSort> goodsSort=cs.selectGoodsSortAsc();
        request.setAttribute ("goods",goods);
        request.setAttribute ("goodsSort",goodsSort);
        return "f:admin/product-list";
    }
    /**
     * 判断该商品是否有详情再考虑上下架
     * @date 2023/4/18
     **/
    public String upOrDown(HttpServletRequest request, HttpServletResponse response)throws Exception{
        Integer gid = Integer.valueOf(request.getParameter("id"));
        List<Detail> did = ds.selectDetailByGid(gid);
        JSONObject json = new JSONObject();
        if(did.size()<1){
            json.put("flag",-1);
        }else {
            json.put("flag",1);
        }
        return json.toJSONString();
    }

    //获取文件后缀名
    public String getSuffix(String oldName){
        //.png/.jpg……
        int i = oldName.lastIndexOf(".");
        return oldName.substring(i);
    }
    //生成唯一的文件名
    public String uniqeName(){
        //获取当前系统时间
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String s=sdf.format(date);
        //生成四位数的随机数  1-9999之间，不够四位的，补齐四位 0001  0025
        int rnd = (int)(Math.random()*9999)+1;
        //rnd=4
        String n = rnd+"";
        for(int i=0;i<(4-n.length());i++){
            n="0"+n;
        }
        return s+n;
    }
}
